package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.BusinessException;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.R;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.YddArticleDto;
import com.itheima.ydd.dto.YddArticleInfo;
import com.itheima.ydd.entity.*;
import com.itheima.ydd.service.*;
import com.itheima.ydd.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/index")
@CrossOrigin
@Slf4j
public class FrontIndexController {

    @Autowired
    private IYddCateService yddCateService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private IYddTagService yddTagService;

    @Autowired
    private IYddLinkService yddLinkService;

    @Autowired
    private IYddAdvimgService yddAdvimgService;

    @Autowired
    private IYddArticleService yddArticleService;

    @Autowired
    private IYddUserService yddUserService;


    /**
     * 首页和全局数据
     *
     * @return
     */
    @GetMapping("/index")
    public ResultData index() {

        //返回数据allCate,config,allTag,allLink,banner,sideBanner,showBanner
        Map<String, Object> data = new HashMap<>();

        //allCate
        List<YddCate> yddCates = yddCateService.list();

        data.put("allCate", yddCates);

        //config
        Map<String, Object> config = new HashMap<>();
        //设置list
        List<Map<String, Object>> list = sysConfigService.getList();
        //设置alldata
        List<SysConfig> allData = sysConfigService.list();
        for (SysConfig sysConfig : allData) {
            if (sysConfig.getId() == 125) {
                List<Map<String, Object>> sysConfig125 = sysConfigService.get125ConfigValue();
                sysConfig.setConfigValue(sysConfig125);
            }
        }
        config.put("list", list);
        config.put("allData", allData);

        data.put("config", config);

        //allTag
        List<YddTag> yddTags = yddTagService.list();
        data.put("allTag", yddTags);

        //allLink
        List<YddLink> yddLinks = yddLinkService.list();
        data.put("allLink", yddLinks);

        //banner
        LambdaQueryWrapper<YddAdvimg> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YddAdvimg::getAdvimgpos, 15);
        List<YddAdvimg> yddAdvimgs = yddAdvimgService.list(wrapper);
        data.put("banner", yddAdvimgs);

        //sideBanner
        LambdaQueryWrapper<YddAdvimg> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(YddAdvimg::getAdvimgpos, 14);
        List<YddAdvimg> yddAdvimgsSide = yddAdvimgService.list(wrapper2);
        data.put("sideBanner", yddAdvimgsSide);

        //showBanner
        LambdaQueryWrapper<YddAdvimg> wrapper3 = new LambdaQueryWrapper<>();
        wrapper3.ne(YddAdvimg::getAdvimgpos, 14);
        wrapper3.ne(YddAdvimg::getAdvimgpos, 15);

        List<YddAdvimg> yddAdvimgsShow = yddAdvimgService.list(wrapper3);
        data.put("showBanner", yddAdvimgsShow);

        return ResultData.ok("",data);
    }


    /**
     * 热门置顶文章数据
     *
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/new")
    public ResultData newData(int page, int limit) {

        Map<String, Object> data = new HashMap<>();
        data.put("desc", "首页大列表");

        //现在的时间
        long now = System.currentTimeMillis();
        System.out.println(System.currentTimeMillis());
        //一周前的时间
        long weekAgo = now - 1000 * 60 * 60 * 24 * 7;
        //一天前的时间
        long dayAgo = now - 1000 * 60 * 60 * 24;

        //获取一周内新的文章数
        LambdaQueryWrapper<YddArticle> wrapper = new LambdaQueryWrapper<>();
        wrapper.between(YddArticle::getCreateDate, weekAgo, now);
        wrapper.eq(YddArticle::getStatus, 2);
        int numWeek = yddArticleService.count(wrapper);
        data.put("num_week", numWeek);

        //获取一天内新的文章数
        LambdaQueryWrapper<YddArticle> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.between(YddArticle::getCreateDate, dayAgo, now);
        wrapper2.eq(YddArticle::getStatus, 2);
        int numDay = yddArticleService.count(wrapper2);
        data.put("num_day", numDay);

        //获取置顶文章
        Page<YddArticle> pageInfo = new Page<>(page, limit);
        LambdaQueryWrapper<YddArticle> wrapper3 = new LambdaQueryWrapper<>();
        wrapper3.orderByDesc(YddArticle::getCreateDate);
        wrapper3.eq(YddArticle::getIstop, 1);
        wrapper3.eq(YddArticle::getStatus, 2);
        yddArticleService.page(pageInfo, wrapper3);
        List<YddArticle> records = pageInfo.getRecords();

        Page<YddArticleInfo> articleDtoPage = new Page<>();
        BeanUtils.copyProperties(pageInfo, articleDtoPage, "records");
        List<YddArticleInfo> yddArticleDtos = records.stream().map(item -> {
            YddArticleInfo yddArticleDto = new YddArticleInfo();
            BeanUtils.copyProperties(item, yddArticleDto);
            LambdaQueryWrapper<YddCate> wrapper4 = new LambdaQueryWrapper<>();
            wrapper4.eq(YddCate::getId, item.getCateid());
            YddCate yddCate = yddCateService.getOne(wrapper4);
            if (yddCate != null) {
                yddArticleDto.setCatename(yddCate.getCatename());
            }
            Date date = new Date(item.getCreateDate());
            Instant instant = date.toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            yddArticleDto.setCreateDate(instant.atZone(zoneId).toLocalDateTime());
            return yddArticleDto;
        }).collect(Collectors.toList());

        //将数据封装为pageResult
        PageResult pageResult = PageResult.getPage(pageInfo);
        pageResult.setData(yddArticleDtos);
        data.put("list", pageResult);

        return ResultData.ok("",data);
    }

    /**
     * 获取最新热门
     *
     * @return
     */
    @GetMapping("/hot")
    public ResultData getHot() {

        Map<String, Object> data = new HashMap<>();
        data.put("desc", "侧边最新文章");

        //获取最新文章
        Page<YddArticle> pageInfo = new Page<>(0, 8);
        LambdaQueryWrapper<YddArticle> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(YddArticle::getLovenum);
        wrapper.orderByDesc(YddArticle::getId);
        wrapper.eq(YddArticle::getStatus, 2);
        ;

        yddArticleService.page(pageInfo, wrapper);

        List<YddArticle> records = pageInfo.getRecords();

        List<YddArticleDto> yddArticleDtos = records.stream().map(item -> {
            YddArticleDto yddArticleDto = new YddArticleDto();
            BeanUtils.copyProperties(item, yddArticleDto);
            LambdaQueryWrapper<YddCate> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(YddCate::getId, item.getCateid());
            YddCate yddCate = yddCateService.getOne(wrapper1);
            if (yddCate != null) {
                yddArticleDto.setCatename(yddCate.getCatename());
            }
            return yddArticleDto;
        }).collect(Collectors.toList());

        data.put("list", yddArticleDtos);

        return ResultData.ok("",data);
    }


    /**
     * 首页侧边推荐文章
     *
     * @return
     */
    @GetMapping("/recommend")
    public ResultData recommend() {


        Map<String, Object> data = new HashMap<>();
        data.put("desc", "侧边推荐文章");

        //获取推荐文章
        Page<YddArticle> pageInfo = new Page<>(0, 6);
        LambdaQueryWrapper<YddArticle> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(YddArticle::getId);
        wrapper.eq(YddArticle::getIshot, 1);
        wrapper.eq(YddArticle::getStatus, 2);
        List<YddArticle> yddArticles = yddArticleService.list(wrapper);

        List<YddArticle> newArticles = new ArrayList<>();

        for (int i = 0; i < 6; i++) {
            newArticles.add(yddArticles.get(i));
        }

        List<YddArticleDto> yddArticleDtos = newArticles.stream().map(item -> {
            YddArticleDto yddArticleDto = new YddArticleDto();
            BeanUtils.copyProperties(item, yddArticleDto);
            LambdaQueryWrapper<YddCate> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(YddCate::getId, item.getCateid());
            YddCate yddCate = yddCateService.getOne(wrapper1);
            if (yddCate != null) {
                yddArticleDto.setCatename(yddCate.getCatename());
            }
            return yddArticleDto;
        }).collect(Collectors.toList());

        data.put("list", yddArticleDtos);

        return ResultData.ok("",data);


    }


    /**
     * 用户注册
     *
     * @param yddUser
     * @return
     */
    @PostMapping("/reg")
    public ResultData register(@RequestBody YddUser yddUser) {

        LambdaQueryWrapper<YddUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YddUser::getMobile, yddUser.getMobile());
        int count = yddUserService.count(wrapper);
        if (count > 0) {
            throw new BusinessException("该手机号已存在!");
        }

        String password = DigestUtils.md5DigestAsHex(yddUser.getPassword().getBytes());

        yddUser.setPassword(password);

        yddUser.setUsername(yddUser.getMobile());

        yddUserService.save(yddUser);

        // 生成token信息
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("userId", yddUser.getId());
        String token = JwtUtils.getToken(tokenMap);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);

        return ResultData.ok("",map);

    }


    /**
     * 分页展示分类下的文章
     *
     * @param page
     * @param limit
     * @param cateid
     * @return
     */
    @GetMapping("/list")
    public ResultData getList(int page, int limit, Integer cateid) {

        Page<YddArticle> pageInfo = new Page<>(page, limit);
        LambdaQueryWrapper<YddArticle> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(YddArticle::getId);
        wrapper.eq(cateid != null, YddArticle::getCateid, cateid);
        yddArticleService.page(pageInfo, wrapper);
        List<YddArticle> records = pageInfo.getRecords();

        List<Map<String, Object>> articles = records.stream().map(item -> {
            Date date = new Date(item.getCreateDate());
            Instant instant = date.toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();

            Map<String, Object> map = new HashMap<>();
            map.put("id", item.getId());
            map.put("title", item.getTitle());
            map.put("author", item.getAuthor());
            map.put("keywords", item.getKeywords());
            map.put("description", item.getDescription());
            map.put("tags", item.getTags());
            map.put("istop", item.getIstop());
            map.put("ishot", item.getIshot());
            map.put("create_date", localDateTime);
            map.put("click", item.getClick());
            map.put("pic", item.getPic());
            map.put("lovenum", item.getLovenum());

            LambdaQueryWrapper<YddCate> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(YddCate::getId, item.getCateid());
            YddCate yddCate = yddCateService.getOne(wrapper1);
            if (yddCate != null) {
                map.put("catename", yddCate.getCatename());
            }
            return map;
        }).collect(Collectors.toList());

        Map<String, Object> data = new HashMap<>();
        Map<String, Object> list = new HashMap<>();
        list.put("data", articles);
        list.put("count", pageInfo.getTotal());
        list.put("totalPages", pageInfo.getPages());
        list.put("currentPage", pageInfo.getCurrent());
        list.put("pageSize", pageInfo.getSize());

        data.put("list", list);

        return ResultData.ok("",data);

    }


    /**
     * 获取文章详情
     *
     * @param id
     * @return
     */
    @GetMapping("/show")
    public ResultData show(Integer id) {


        Map<String, Object> data = new HashMap<>();

        //获取前一篇文章title
        List<Map<String, Object>> prev = new ArrayList<>();
        YddArticle prevArticle = null;
        int i = id - 1;
        while (prevArticle == null && i > 0) {
            prevArticle = yddArticleService.getById(i);
            i--;
        }
        Map<String, Object> prevMap = new HashMap<>(2);
        if (prevArticle != null) {
            prevMap.put("id", i+1);
            prevMap.put("title", prevArticle.getTitle());
            prev.add(prevMap);
        }
        data.put("prev", prev);
        //获取后一篇文章title
        List<Map<String, Object>> next = new ArrayList<>();
        YddArticle nextArticle = null;
        int j = id + 1;
        while (nextArticle == null && j > 0) {
            nextArticle = yddArticleService.getById(j);
            if(nextArticle ==null){
                LambdaQueryWrapper<YddArticle> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.gt(YddArticle::getId,j);
                int count = yddArticleService.count(lambdaQueryWrapper);
                if (count<=0){
                    break;
                }
            }
            j++;
        }
        Map<String, Object> nextMap = new HashMap<>(2);
        if (nextArticle != null) {
            nextMap.put("id", j-1);
            nextMap.put("title", nextArticle.getTitle());
            next.add(nextMap);
        }
        data.put("next", next);

        //获取推荐文章
        Page<YddArticle> pageInfo = new Page<>(0, 4);
        LambdaQueryWrapper<YddArticle> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(YddArticle::getId);
        wrapper.eq(YddArticle::getIshot, 1);
        wrapper.eq(YddArticle::getStatus, 2);
        yddArticleService.page(pageInfo, wrapper);
        List<YddArticle> records = pageInfo.getRecords();

        List<Map<String, Object>> recommend = records.stream().map(item -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", item.getId());
            map.put("title", item.getTitle());
            map.put("pic", item.getPic());
            map.put("cateid", item.getCateid());

            LambdaQueryWrapper<YddCate> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(YddCate::getId, item.getCateid());
            YddCate yddCate = yddCateService.getOne(wrapper1);
            if (yddCate != null) {
                map.put("catename", yddCate.getCatename());
            }
            return map;
        }).collect(Collectors.toList());

        data.put("recommend", recommend);


        //获取info
        YddArticle article = yddArticleService.getById(id);
        LambdaQueryWrapper<YddCate> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(YddCate::getId, article.getCateid());
        YddCate yddCate = yddCateService.getOne(wrapper1);
        YddArticleInfo yddArticleDto = new YddArticleInfo();
        BeanUtils.copyProperties(article, yddArticleDto);
        yddArticleDto.setCatename(yddCate.getCatename());
        Date date = new Date(article.getCreateDate());
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        yddArticleDto.setCreateDate(instant.atZone(zoneId).toLocalDateTime());

        data.put("info", yddArticleDto);

        return ResultData.ok("",data);

    }


}
